package com.spzx.product.configure;

import io.netty.util.concurrent.DefaultThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolConfig {
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        //获取当前配置的处理器核心数
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        //设置最大线程数
        int maxPoolSize = corePoolSize * 2;
        //设置存活时间
        Long keepAliveTime = 60L;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                Executors.defaultThreadFactory(),
                (runnable, executor) -> {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                    }
                    //再次尝试提交
                    executor.submit(runnable);
                }
        );
        return threadPoolExecutor;
    }
}
